// 获取请求地址
var apiList = {
	base: 'http://nbtmsserver.cloud.yunku.live:1001/WebTMSPhoneServers.aspx'
};
// 应用版本
var version = "1.0.0";
//页面展示条数
var rows = 20;
var userInfo = null;

// 获取本地存储用户信息
function getLocalUserInfo() {
	var user = localStorage.getItem('user_info');
	if(!user || user == 'undefined') return null;
	return JSON.parse(user);
}
// 设置本地存储用户信息
function setLocalUserInfo(info) {
	userInfo = info;
	localStorage.setItem('user_info', JSON.stringify(info));
}

// 初始化用户信息
if(localStorage.getItem('user_info')) {
	userInfo = getLocalUserInfo();
}

var baseApi = {};
mui.each(['get', 'post'], function(index, method) {
	baseApi[method] = function(params, callback, errorCallBack) {
		if(userInfo) {
			params.user_id = userInfo.userid;
			params.system = "android";
		}
		if(typeof params === 'object') {
			params = {
				p: JSON.stringify(params)
			};

			console.log(JSON.stringify(params));
		}

		if(!isHaveNet()) {
			mui.toast("网络连接失败！请检查网络连接！");
			return;
		}

		return $.ajax({ 
			url: getRequestAddressUrl('base'),
			type: 'POST',
			data: params,
			dataType: 'json',
			beforeSend: function () {
				plus.nativeUI.showWaiting();
			},
			error: function (res) {
				plus.nativeUI.closeWaiting();
				console.log(JSON.stringify(res));
			},
			success: function(result) {
				plus.nativeUI.closeWaiting();
				console.log(JSON.stringify(result));
				if(result.status == 0) {
					if(errorCallBack) {
						errorCallBack();
					}
					mui.toast(result.err_msg);
				} else {
					console.log(callback.name, JSON.stringify(result));
					return callback(result);
				}
			}
		});
	};
});

// 页面跳转
$('.open-url').on('tap', function() {
	var url = $(this).is('a') ? $(this).attr('href') : $(this).data('url');
	var data = $(this).data();
	delete data.url;
	delete data.href;
	
	data.prevWebviewId = plus.webview.currentWebview().id;
	
	pageChange({
		pageUrl: url,
		createNew: false,
		postData: data
	});
	return false;
});

// 图片的请求地址
//var filesHost = getRequestAddressUrl("filesHost");
var loginid = window.localStorage.getItem("uid");
//var loginid = "1000171372";

// 检查登陆状态
function checkUserLogin() {
	if(!userInfo && /(login|register)\.html/.test(location.href) === false) {
		pageChange({
			pageUrl: "../user/login.html",
			createNew: true,
			postData: {
				referer: location.href
			}
		});
	}
}

// 关闭所有页面
function clearAllWindows() {
	var all = plus.webview.all();
	for(key in all) {
		if(all[key] !== plus.webview.currentWebview()) {
			plus.webview.close(all[key]);
		}
	}
}

// 关闭当前页面
function closeCurrentWindow() {
	plus.webview.close(plus.webview.currentWebview());
}

// 退出登录
function userLogout() {
	userInfo = null;
	localStorage.setItem('user_info', null);
	checkUserLogin();
}

// 用户信息更新
function userInfoUpdate(info) {
	if(info) {
		setLocalUserInfo(info);
	} else {
		baseApi.get({
			op: 'getuserinfo'
		}, function(result) {
			setLocalUserInfo(result);
		});
	}
}

mui.plusReady(function() {
	console.log(JSON.stringify(userInfo));
	// 存储父页面webViewId
	if(mui("#parentWebViewId").length == 0) {
		var inputBox = document.createElement('input');
		inputBox.id = "parentWebViewId";
		inputBox.style.display = "none";
		inputBox.type = "text"
		inputBox.value = (getQueryString("webViewId")) ? getQueryString("webViewId") : "";
		document.body.appendChild(inputBox);
	} else {
		mui("#parentWebViewId")[0].value = (getQueryString("webViewId")) ? getQueryString("webViewId") : "";
	}
});
//changeWindowWidth();

var cssEl = document.createElement('style');
document.documentElement.firstElementChild.appendChild(cssEl);

function setPxPerRem(clientWidth) {
	var dpr = 1;
	//把viewport分成15份的rem，html标签的font-size设置为1rem的大小;

	if(!clientWidth) {
		clientWidth = document.documentElement.clientWidth;
	}

	var pxPerRem = clientWidth * dpr / 15;
	cssEl.innerHTML = 'html{font-size:' + pxPerRem + 'px!important;}';
}

var clientWidth = 0;
var clientHeight = 0;

function changeWindowWidth() {
	if(!clientWidth) {
		clientWidth = document.documentElement.clientWidth;
		clientHeight = document.documentElement.clientHeight;
	}
	if(navigator.platform.indexOf("Win32") || clientHeight < clientWidth) {
		document.getElementsByTagName("body")[0].style.width = "320px";
	} else {
		document.getElementsByTagName("body")[0].style.width = clientWidth + "px";
	}

}

// 处理横屏竖屏事件
var evt = "onorientationchange" in window ? "orientationchange" : "resize";
window.addEventListener(evt, function() {
	// 竖屏
	if(window.orientation === 180 || window.orientation === 0) {
		if(typeof orientation180 == "function") {
			orientation180();
		}
	}
	// 横屏
	if(window.orientation === 90 || window.orientation === -90) {
		if(typeof orientation90 == "function") {
			orientation90();
		}
	}
}, false);
// 是否竖屏显示
// flg：true竖屏显示
function lockOrientation(flg) {
	if(flg) {
		plus.screen.lockOrientation("portrait-primary");
	}
}

// mui全局处理
mui.init({
	beforeback: function() {
		// 页面回调方法                                                        
		if(typeof beforeback === 'function') {
			beforeback.call();
		}
	}
});

// 设置json默认值
// defaults：默认值
// settings：返回值
function extendSettings(defaults, settings) {
	if(typeof(settings) != "object") {
		return defaults;
	} else {
		for(var o in defaults) {
			var addflg = true;
			var addobj;
			for(var n in settings) {
				if(o == n) {
					addflg = false;
					addobj = "";
					break;
				} else {
					addobj = o;
				}
			}

			if(addflg) {
				settings[addobj] = defaults[addobj];
			}
		}

		return settings;
	}
}
// 事件绑定
// settings.eventId：对象id
// settings.eventType：事件绑定类型，默认tap
// settings.eventFunction：触发方法体
function elementBindEvent(settings) {
	var defaults = {
		eventType: "tap"
	};
	settings = extendSettings(defaults, settings);
	mui("#" + settings.eventId)[0].addEventListener(settings.eventType, function() {
		if(settings.eventFunction) {
			settings.eventFunction.call('', this);
		}
	})
};
// 群组上事件
// settings.eventObj：父容器id
// settings.eventType：事件绑定类型
// settings.targetObj：带绑定控件组样式
// settings.eventFunction：触发方法体
function elementBindEventByObj(settings) {
	var defaults = {
		eventType: "tap"
	};
	settings = extendSettings(defaults, settings);
	mui("#" + settings.eventObj).on(settings.eventType, "." + settings.targetObj, function() {
		if(settings.eventFunction) {
			settings.eventFunction.call('', this);
		}
	})
};
// 页面跳转
// settings.pageUrl：页面url
// settings.postData：目标页面参数
// settings.aniShow：页面加载动态效果,默认为slide-in-right
function pageChange(settings) {
	if(!settings.postData) {
		settings.postData = {};
	}
	settings.postData.webViewId = plus.webview.currentWebview().id;
	var defaults = {
		aniShow: "slide-in-right",
		createNew: false
	};
	settings = extendSettings(defaults, settings);
	var isCreate = false;

	mui.openWindow({
		id: settings.pageUrl,
		url: settings.pageUrl,
		show: {
			autoShow: true, //页面loaded事件发生后自动显示，默认为true      
			aniShow: settings.aniShow, //页面显示动画，默认为”slide-in-right“；      
			duration: 200 //页面动画持续时间，Android平台默认100毫秒，iOS平台默认200毫秒；    
		},
		createNew: settings.createNew,
		waiting: {
			autoShow: false
		},
		extras: settings.postData
	});
};
// 获取请求参数
// name：参数名称
function getQueryString(name) {
	var self = plus.webview.currentWebview();
	var value = self[name];
	if(isEmpty(value)) {
		value = ""
	}
	return value;
};
//生成32位随机码
function newGuid() {
	var guid = "";
	for(var i = 1; i <= 32; i++) {
		var n = Math.floor(Math.random() * 16.0).toString(16);
		guid += n;
	}
	return guid;
};
// 获取请求地址
function getRequestAddressUrl(key) {
	return apiList[key];
};

// 组合json
function jsonjoin(sorJosn, tarJosn) {
	sorJosn.push = function(o) {
		if(typeof(o) == 'object')
			for(var p in o) this[p] = o[p];
	};
	sorJosn.push(
		tarJosn
	)

	return sorJosn;
};
// 调用父webview方法
// funName：方法名
// params：参数
function callParentWebViewFun(funName, params) {
	if(!params) {
		params = {};
	}
	var pageid = mui("#parentWebViewId")[0].value;
	mui.fire(plus.webview.getWebviewById(pageid), funName, params);
};

// 获取相邻元素(内部方法)
function getNearEle(ele, type) {
	type = type == 1 ? "previousSibling" : "nextSibling";
	var nearEle = ele[type];
	while(nearEle) {
		if(nearEle.nodeType === 1) {
			return nearEle;
		}
		nearEle = nearEle[type];
		if(!nearEle) {
			break;
		}
	}
	return null;
}
// 获取当前对象的上一个元素
// ele：当前对象
function prev(ele) {
	return getNearEle(ele, 1);
}
// 获取当前对象的下一个元素
// ele：当前对象
function next(ele) {
	return getNearEle(ele, 0);
}
// 获得匹配元素集合中每个元素前面的所有同胞元素
// ele：当前对象
// tarEle：查询的对象类型
function prevAll(ele, tarEle) {
	var prevEles = [];
	var ele = getNearEle(ele, 1);
	return pushEle(prevEles, ele, tarEle);

	function pushEle(prevEles, ele, tarEle) {
		if(ele) {
			if(tarEle) {
				if(ele.nodeName.toLowerCase() == tarEle || ele.className.indexOf(tarEle) != -1 || ele.id == tarEle) {
					prevEles.push(ele);
					ele = getNearEle(ele, 1);
					pushEle(prevEles, ele, tarEle);
				} else {
					ele = getNearEle(ele, 1);
					pushEle(prevEles, ele, tarEle);
				}
			} else {
				prevEles.push(ele);
				ele = getNearEle(ele, 1);
				pushEle(prevEles, ele, tarEle);
			}
		}
		return prevEles;
	}
}
// 获得匹配元素集合中每个元素的所有跟随的同胞元素
// ele：当前对象
// tarEle：查询的对象类型
function nextAll(ele, tarEle) {
	var nextEles = [];
	var ele = getNearEle(ele, 0);
	return pushEle(nextEles, ele, tarEle);

	function pushEle(nextEles, ele, tarEle) {
		if(ele) {
			if(tarEle) {
				if(ele.nodeName.toLowerCase() == tarEle || ele.className.indexOf(tarEle) != -1 || ele.id == tarEle) {
					nextEles.push(ele);
					ele = getNearEle(ele, 0);
					pushEle(nextEles, ele, tarEle);
				} else {
					ele = getNearEle(ele, 0);
					pushEle(nextEles, ele, tarEle);
				}
			} else {
				nextEles.push(ele);
				ele = getNearEle(ele, 0);
				pushEle(nextEles, ele, tarEle);
			}
		}
		return nextEles;
	}
}
// 当前对象前插入元素、newEle放到tarEle前面
function insertBefore(newEle, tarEle) {
	var parent = tarEle.parentNode;
	if(!parent) {
		parent = tarEle;
	}
	parent.insertBefore(newEle, tarEle);
}
// 当前对象后插入元素、newEle放到tarEle后面
function insertAfter(newEle, tarEle) {
	var parent = tarEle.parentNode;
	if(!parent) {
		parent = tarEle;
	}
	if(parent.lastChild == tarEle) {
		parent.appendChild(newEle);
	} else {
		parent.insertBefore(newEle, tarEle.nextSibling);
	}
}
// 获取指定元素 ele.find(tarEle)
function find(ele, tarEle) {
	var tarEles = [];
	var nodes = ele.childNodes;
	return getEle(tarEles, nodes, tarEle);

	function getEle(tarEles, nodes, tarEle) {
		for(var i = 0; i < nodes.length; i++) {
			if(nodes[i].nodeName.toLowerCase() == tarEle || nodes[i].className == tarEle || nodes[i].id == tarEle) {
				tarEles.push(nodes[i]);
				getEle(tarEles, nodes[i].childNodes, tarEle);
			} else {
				getEle(tarEles, nodes[i].childNodes, tarEle);
			}
		}
		return tarEles;
	}
}
// 获取元素位置
// tarEle：当前元素
function index(tarEle) {
	var parent = tarEle.parentNode;
	var eleArr = parent.childNodes;
	var index = 0;
	for(var i = 0; i < eleArr.length; i++) {
		if(eleArr[i] == tarEle) {
			index = i;
			break;
		}
	}
	return index;
}
// 移除元素
// ele:当前元素
function remove(ele) {
	var parent = ele.parentNode;
	parent.removeChild(ele);
}
// 循环数组
function foreach(array, func) {
	for(var i = 0; i < array.length; ++i) {
		func(array[i]);
	}
};
// 滚动到对象底部
function scrollBottom(obj) {
	obj.scrollTop = obj.scrollHeight;
}
// 加载模板H5用
//languageUrl:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//templateUrl:模板配置文件名称，命名规范"template_模块名_页面模板名称（可选）",注：不用传文件后缀
//templateId:需要模板展现的父容器id
//loadFunction:模板加载完成后回调方法
//parameters：回调方法参数
function getTemplate(settings) {
	localStorage[settings.languageUrl] = "";
	var appurl = window.location.pathname.split('www')[0] + "www/";
	var languageType = plus.os.language.split('-')[0].toLowerCase();
	var languageData;
	var appAjaxLanguage = new XMLHttpRequest();
	appAjaxLanguage.open('GET', appurl + settings.languageUrl + "_" + languageType + ".properties", true);
	appAjaxLanguage.send(null);
	appAjaxLanguage.onreadystatechange = function() {
		if(appAjaxLanguage.readyState == 4) {
			languageDate = eval("(" + appAjaxLanguage.responseText + ")");
			localStorage[settings.languageUrl] = appAjaxLanguage.responseText;
			var appAjax = new XMLHttpRequest();
			appAjax.open('GET', appurl + settings.templateUrl + ".html", true);
			appAjax.send(null);
			appAjax.onreadystatechange = function() {
				if(appAjax.readyState == 4) {
					var responseData = appAjax.responseText;

					responseData = changenDataByLanguage(responseDate, languageData);

					document.getElementById(settings.templateId).innerHTML = responseData;

					if(settings.loadFunction) {
						settings.loadFunction.call(null, settings.parameters, languageData);
					}
					appAjax = null;
				}
			}

			appAjaxLanguage = null;
		}
	}
};
// 获取国际化信息原生用
//languageUrl:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//languageData：返回国际化信息（json格式）
function getLanguageDataNative(settings) {
	localStorage[settings.languageUrl] = "";
	var appurl = window.location.pathname.split('www')[0] + "www/";
	var languageType = plus.os.language.split('_')[0].toLowerCase();
	var languageUrl = appurl + settings.languageUrl + "_" + languageType + ".properties";

	plus.io.requestFileSystem(plus.io.PRIVATE_WWW, function(fs) {
		fs.root.getFile(languageUrl, {
			create: true
		}, function(fileEntry) {
			fileEntry.file(function(file) {
				var fileReader = new plus.io.FileReader();
				fileReader.readAsText(file, 'utf-8');
				fileReader.onloadend = function(evt) {
					localStorage[settings.languageUrl] = evt.target.result;
				};
			});
		});
	});
	setTimeout(function() {
		settings.languageDataFn.call('', getLanguageDataAgain(settings.languageUrl, settings));
	}, 100)

};
// 单独获取国际化信息
//key:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//languageData：返回国际化信息（json格式）
function getLanguageDataAgain(key, settings) {
	//	console.log("key"+key);
	if(localStorage[key] != "") {
		return eval("(" + localStorage[key] + ")");
	} else {
		return getLanguageDataNative(settings);
	}
}

// 加载模板原生用
//languageUrl:国际化配置文件名称，命名规范"language_模块名_页面模板名称（可选）",注：不用传语言类型、文件后缀
//templateUrl:模板配置文件名称，命名规范"template_模块名_页面模板名称（可选）",注：不用传文件后缀
//templateId:需要模板展现的父容器id
//loadFunction:模板加载完成后回调方法
//parameters：回调方法参数
function getTemplateNative(settings) {
	localStorage[settings.languageUrl] = "";
	var appurl = window.location.pathname.split('www')[0] + "www/";
	var languageType = plus.os.language.split('_')[0].toLowerCase();
	var languageUrl = appurl + settings.languageUrl + "_" + languageType + ".properties";
	var templateUrl = appurl + settings.templateUrl + ".html";

	plus.io.requestFileSystem(plus.io.PRIVATE_WWW, function(fs) {
		fs.root.getFile(languageUrl, {
			create: true
		}, function(fileEntry) {
			fileEntry.file(function(file) {
				var fileReader = new plus.io.FileReader();
				fileReader.readAsText(file, 'utf-8');
				fileReader.onloadend = function(evt) {
					var languageData = eval('(' + evt.target.result + ')');
					localStorage[settings.languageUrl] = evt.target.result;
					fs.root.getFile(templateUrl, {
						create: true
					}, function(fileEntry) {
						fileEntry.file(function(file) {
							var fileReader = new plus.io.FileReader();
							fileReader.readAsText(file, 'utf-8');
							fileReader.onloadend = function(evt) {
								var responseData = changenDataByLanguage(evt.target.result, languageData);
								document.getElementById(settings.templateId).innerHTML = responseData;

								if(settings.loadFunction) {
									settings.loadFunction.call(null, settings.parameters, languageData);
								}
							}
						})
					})
				}
			});
		});
	});
}

// 替换语言信息
function changenDataByLanguage(responseData, languageData) {
	for(var o in languageData) {
		responseData = responseData.replace(new RegExp("\\{{" + o + "\\}}", "g"), languageData[o]);
	}
	return responseData;
}

//格式化时间 服务器返回时间格式为yyyyMMddHHmmssSSS 17位字符串
//将服务器时间修改为yyyy-MM-dd HH:mm 的基本格式
function formatCreateTimeByBase(createTime) {
	if(!createTime) {
		console.log("时间传入值为空。");
		return;
	}
	if(createTime.length > 12) {
		var year = createTime.slice(0, 4);
		var month = createTime.slice(4, 6);
		var day = createTime.slice(6, 8);
		var hour = createTime.slice(8, 10);
		var minute = createTime.slice(10, 12)
		var newTimeStr = year + "-" + month + "-" + day + " " + hour + ":" + minute;
		return newTimeStr;
	} else {
		return createTime;
	}
}

//格式化时间 
//dateTime 需要格式化的时间（格式为：2016-08-05 11:00:00）
// 格式化之后返回时间的格式为：2016年08月05日 11:00
function formatDateTime(dateTime) {
	console.log("dateTime------>" + dateTime);
	if(!dateTime) {
		console.log("时间传入值为空。");
		return;
	}
	if(dateTime.length == 19) {
		var year = dateTime.slice(0, 4);
		var month = dateTime.slice(5, 7);
		var day = dateTime.slice(8, 10);
		var hour = dateTime.slice(11, 13);
		var minute = dateTime.slice(14, 16)
		var newTimeStr = year + "年" + month + "月" + day + "日 " + hour + ":" + minute;
		return newTimeStr;
	} else {
		return dateTime;
	}
}

//格式化时间 服务器返回时间格式为yyyyMMddHHmmssSSS 17位字符串
//将服务器时间修改为yyyy年MM月dd日 HH:mm 的基本格式
//createTime 服务器返回时间
// value 国际化后的时间标志 （年，月，日）
function formatCreateTimeByChina(createTime) {
	if(!createTime) {
		console.log("时间传入值为空。");
		return;
	}
	if(createTime.length > 12) {
		var year = createTime.slice(0, 4);
		var month = createTime.slice(4, 6);
		var day = createTime.slice(6, 8);
		var hour = createTime.slice(8, 10);
		var minute = createTime.slice(10, 12)
		var newTimeStr = year + "年" + month + "月" + day + "日 " + hour + ":" + minute;
		return newTimeStr;
	} else {
		return createTime;
	}
}

/**
 * Description: 加载缓存
 *    后台返回值格式：{"info":[{"codeclass":"XBDM","version":0,"data":[{"code":"1","codedesc":"男"},{"code":"2","codedesc":"女"}]},{"codeclass":"XXDM","version":0,"data":[{"code":"1","codedesc":"A"},{"code":"2","codedesc":"B"}]}]}
 * @param codeclass_arr 将要加载至缓存的codeclass代码组织成数组形式参数
 */
function setCodeMap(codeclass_arr, callback) {
	var url = getRequestAddressUrl("codemap");
	var param_json = {};
	for(var j = 0; j < codeclass_arr.length; j++) {
		param_json[codeclass_arr[j]] = getCodeClassVersion(codeclass_arr[j]);
	}
	var param_str = JSON.stringify(param_json);
	$.ajax({
		type: "POST",
		url: url,
		data: "clv=" + param_str,
		dataType: "json",
		success: function(data) {
			if(data.info != undefined && data.info != null && data.info.length > 0) {
				for(var i = 0; i < data.info.length; i++) {
					var codeClass = data.info[i].codeclass;
					delete data.info[i]["codeclass"];
					store.setItem(codeClass, "{\"data\":" + JSON.stringify(data.info[i].data) + ",\"version\":" + JSON.stringify(data.info[i].version) + "}");
				}
			}
			if(callback != undefined && callback != null) {
				callback();
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			return;
		}
	});
}
//定义字段
var store = window.localStorage;
/**
 * Description:获取codeclass当前缓存版本信息
 * @param codeclass
 * @returns
 */
function getCodeClassVersion(codeclass) {
	var codeclass_json = store.getItem(codeclass);

	if(codeclass_json == undefined) {
		return -1;
	}
	if(typeof codeclass_json == 'string') {
		codeclass_json = eval("(" + codeclass_json + ")");
	}
	if(!codeclass_json.data) {
		return -1;
	}

	return codeclass_json.version;
};

/**
 * Description: 获取codedesc,未找到对应desc返回undefined
 * @param codeclass
 * @param code
 * @returns
 */
function getCodeDescByCodeClass(codeclass, code) {
	if(!code) return code;
	var codes = code.split(",");
	var codeclass_json = store.getItem(codeclass);
	if(!codeclass_json) return code;
	if(typeof codeclass_json == 'string') {
		codeclass_json = eval("(" + codeclass_json + ")");
	}
	var code_arr = codeclass_json.data;
	if(codeclass_json.data == undefined) {
		code_arr = codeclass_json;
	}
	var codesdesc = "";
	for(var i = 0; i < code_arr.length; i++) {
		for(var j = 0; j < codes.length; j++) {
			if(code_arr[i].code == codes[j].replace(/(^\s*)|(\s*$)/g, "")) {
				codesdesc += code_arr[i].codedesc + ",";
			}
		}
	}
	if(codesdesc != "") {
		return codesdesc.substring(0, codesdesc.length - 1);
	} else {
		return code;
	}
};

/**
 * 设置默认头像
 * 
 * */
function setDefalutPhoto(value) {
	var photo = "../../../ui/common/images/moren1.png";
	if(!isEmpty(value)) {
		photo = filesHost + value;
	} else {
		photo = "../../../ui/common/images/moren1.png";

	}

	return photo;
}
/**
 * 非空判断
 * 判断传入值是否为 null，undefined，“”,返回true/false
 * */
function isEmpty(value) {
	var flg = false;
	if(value == undefined || value == "" || value == null || value == "none" || value == NaN) {
		flg = true;
	}

	return flg;
}
/**
 * 非空判断
 * 传入数组判断
 * */
function isEmptyArray(value) {
	var flg = false;
	for(var i = 0; i < value.length; i++) {
		if(isEmpty(value[i])) {
			flg = true;
			console.log("入参第" + (i + 1) + "个位空，或不存在");
			break;
		}
	}
	return flg;
}

/**
 * 非空判断
 * 传入数组判断
 * */
function getEmptyIndexByArray(value) {
	var index = -1;
	for(var i = 0; i < value.length; i++) {
		if(isEmpty(value[i])) {
			index = i;
			break;
		}
	}
	return index;
}

/**
 * 网络判断
 * */
function getNetWorkState() {
	var netStateStr = '未知';
	var types = {};
	types[plus.networkinfo.CONNECTION_UNKNOW] = "未知";
	types[plus.networkinfo.CONNECTION_NONE] = "无网络";
	types[plus.networkinfo.CONNECTION_ETHERNET] = "有线网络";
	types[plus.networkinfo.CONNECTION_WIFI] = "WiFi";
	types[plus.networkinfo.CONNECTION_CELL2G] = "2G";
	types[plus.networkinfo.CONNECTION_CELL3G] = "3G";
	types[plus.networkinfo.CONNECTION_CELL4G] = "4G";
	netStateStr = types[plus.networkinfo.getCurrentType()];
	return netStateStr;
};

function isHaveNet() {
	var flg = true;
	var netStateStr = getNetWorkState()
	if(netStateStr == "未知" || netStateStr == "无网络") {
		flg = false;
		mui.toast("请检查网络连接");
	}
	return flg;
}

/***
 *  根据传入的文件类型，返回对应的横版image图标SRC 
 * @param {Object} fileType :文件类型
 */
/***
 * 根据传入的文件类型，返回对应的竖版image图标SRC 
 */
function getBigIconByType(fileList, position) {
	var fileInfo = fileList[position];
	var gs1 = fileInfo.format;
	return getBigIconByFormat(gs1, fileInfo);
}

function getBigIconByFormat(gs1, fileInfo) {
	var gs = gs1.toLowerCase();
	var src = '../../../ui/common/images/';

	if(gs == "png" || gs == "jpg" || gs == "gif" || gs == "bmp") {
		if(fileInfo) {
			src = fileInfo.address;
			return filesHost + src;
		} else {
			return src + 'file_image.png';
		}
	} else if(gs == 'xls' || gs == 'xlsx') {
		return src + 'file_xls.png';
	} else if(gs == 'flv' || gs == 'swf') {
		return src + 'file_ani.png';
	} else if(gs == 'flash') {
		return src + 'file_flash.png';
	} else if(gs == 'mp3' || gs == 'wma' || gs == 'midi' || gs == 'aac' || gs == 'wav') {
		return src + 'file_audio.png';
	} else if(gs == 'doc' || gs == 'docx') {
		return src + 'file_doc.png';
	} else if(gs == 'ppt' || gs == 'pptx') {
		return src + 'file_ppt.png';
	} else if(gs == 'txt') {
		return src + 'file_txt.png';
	} else if(gs == 'mp4' || gs == 'avi' || gs == 'wma' || gs == 'rmvb' || gs == '3gp' || gs == 'mid') {
		return src + 'file_video.png';
	} else if(gs == 'zip' || gs == 'rar' || gs == 'jar' || gs == 'aar') {
		return src + 'file_zip.png';
	} else if(gs == 'pdf') {
		return src + 'file_pdf.png';
	} else if(gs == '') {
		return src + 'file_other.png';
	} else {
		return src + 'file_other.png';
	}
}

/**
 * 通过文件类型或去文件对应的小图标的方法
 * @param {Object} fileList 文件信息列表
 * @param {Object} position 选中的文件下标
 */
function getSmallIconByType(fileList, position) {
	var fileInfo = fileList[position];

	return getSmallIconByFormat(gs, fileInfo);
}

function getSmallIconByFormat(gs1, fileInfo) {
	var gs = gs1.toLowerCase();
	var src = '../../../ui/common/images/';

	if(gs == "png" || gs == "jpg" || gs == "gif" || gs == "bmp") {
		if(fileInfo) {
			src = fileInfo.address;
			return filesHost + src;
		} else {
			return src + 's_img.png';
		}

	} else if(gs == 'xls' || gs == 'xlsx') {
		return src + 's_xls.png';
	} else if(gs == 'flv' || gs == 'flash' || gs == 'swf') {
		return src + 's_animate.png';
	} else if(gs == 'mp3' || gs == 'wma' || gs == 'midi' || gs == 'aac' || gs == 'wav') {
		return src + 's_audio.png';
	} else if(gs == 'doc' || gs == 'docx') {
		return src + 's_word.png';
	} else if(gs == 'ppt' || gs == 'pptx') {
		return src + 's_ppt.png';
	} else if(gs == 'txt') {
		return src + 's_cource.png';
	} else if(gs == 'mp4' || gs == 'avi' || gs == 'wma' || gs == 'rmvb' || gs == '3gp' || gs == 'mid') {
		return src + 's_video.png';
	} else if(gs == 'zip' || gs == 'rar' || gs == 'jar' || gs == 'aar') {
		return src + 's_zip.png';
	} else if(gs == 'pdf') {
		return src + 's_pdf.png';
	} else if(gs == '') {
		return src + 's_other.png';
	} else {
		return src + 's_other.png';
	}
}

/**
 * 文件上传调用的方法
 */
//传入参数
//files：文件地址数组
//upload_abs_path： "wdcloud-rrt/rest/fileWS/upload"文件服务器上传接口 
//successCallBack:function(data)  上传成功时的回调函数 data参数为服务器返回的json数据
//failCallBack:function(status)  上传失败时的回调函数
//cd  附件的长度
/**
 * @修改时间 2016/09/22 19:20
 * 修改者:zgq
 * 修改内容:增加一个参数:num_i :第几张图片
 * 照片上传修改为多张上传
 */
//var uploadhost = getRequestAddressUrl("filesUploader");
var upload_abs_path = "upload";

var sucess_num = 0;
var fail_num = 0;

function uploadFiles(settings, cd, num_i) {
	if(!settings) {
		console.log("传入参数不存在");
		return;
	};
	//	var w = plus.nativeUI.showWaiting();
	if(!isEmpty(num_i)) {
		if(num_i == cd) {
			mui.toast("正在上传文件...");
		}
	} else {
		mui.toast("正在上传文件...");
	}
	var files = settings.files;
	if(files.length <= 0) {
		plus.nativeUI.alert("没有添加上传文件！");
		return;
	}
	if(settings.upload_abs_path) {
		upload_abs_path = settings.upload_abs_path;
	}
	console.log("hostpath--->>" + uploadhost + upload_abs_path);
	var task = plus.uploader.createUpload(uploadhost + upload_abs_path, {
			method: "POST"
		},
		function(t, status) { //上传完成 
			console.log("status->" + status);
			if(status == 200) {
				//				plus.nativeUI.closeWaiting();
				//				plus.nativeUI.toast("上传成功");
				var resp = JSON.parse(t.responseText); // 干些后续处理
				if(settings.successCallBack) {
					settings.successCallBack.call('', resp);
				}
				sucess_num++;
				if((sucess_num + fail_num) == cd) {
					mui.toast("上传成功:" + sucess_num + ",失败:" + fail_num);
					sucess_num = 0;
					fail_num = 0;
				}
			} else {
				//				plus.nativeUI.closeWaiting();
				//				plus.nativeUI.toast("上传失败：");
				if(settings.failCallBack) {
					settings.failCallBack.call('', status);
				}
				fail_num++;
				if((sucess_num + fail_num) == cd) {
					mui.toast("上传成功:" + sucess_num + ",失败:" + fail_num);
					sucess_num = 0;
					fail_num = 0;
				}
			}
		}
	);
	for(var i = 0; i < files.length; i++) {
		var f = files[i];
		var path = plus.io.convertAbsoluteFileSystem(f);
		console.log("----filedizhi----------->" + f.toString());
		var length = f.split("/").length - 1;
		var key = f.split("/")[length];
		console.log("fileskey---->>" + key);

		task.addFile(path, {
			key: "files"
		});
		task.addData();
		task.start();
	}
	//	if(task) {
	//		task.start();
	//	} else {
	//		console.log("任务创建失败");
	//	};

}
/**
 * 
 * kb转mb
 */
function kBToMB(b) {
	if(isEmpty(b)) { //b shi kong
		return("0B");
	}
	b = parseInt(b);
	var kb = "";
	var mb = "";
	var gb = "";
	if(b < 1024) { //b
		return(b + "B");
	} else if(b >= 1024 && b < (1024 * 1024)) { //k
		if(b % 1024 == 0) {
			kb = b / 1024;
		} else {
			kb = Math.round(b / 1024);
		}
		return kb + "KB";
	} else if(b >= (1024 * 1024) && b < (1024 * 1024 * 1024)) { //m
		if(b % (1024 * 1024) == 0) {
			mb = b / (1024 * 1024);
		} else {
			mb = Math.round(b / (1024 * 1024));
		}
		return mb + "M";
	} else { //G
		if(b % (1024 * 1024 * 1024) == 0) {
			gb = b / 1024 / 1024 / 1024;
		} else {
			gb = gb + "";
			var i = gb.indexOf(".");
			gb = gb.substring(0, i + 2);
		}
		return gb + "G";
	}
}
/**
 * 
 * 四舍五入
 */
function rounding(size) {
	var size = size + "";
	var num = "";
	if(size.length >= 3) {
		var third = size.substring(2, 3);
		size = size.substring(0, 1);
		num = parseInt(size);
		if(third > 5) {
			num = num + 1;
		}
	} else {
		num = parseInt(size);
	}
	return num;
}
/**
 * 
 * 年-月-日
 */
function timeFormat(time) {
	var time = time + "";
	if(time == null || time == undefined || time == "") {
		time = ""
		return time;
	}

	if(time.length > 10) {
		time = time.substring(0, 10);
	}
	return time;
}
/**
 * 获取拼接的eq
 * @param {Object} array
 */
function getEqString(myMap) {
	var eqStr = "";

	for(var i = 0; i < myMap.length; i++) {
		if(!isEmpty(myMap[i].text) && !isEmpty(myMap[i].value) && myMap[i].text != "undefined" && myMap[i].value != "undefined") {
			eqStr = eqStr + myMap[i].text + ":" + myMap[i].value + ";";
		}
	}
	if(!isEmpty(eqStr)) { //有值
		eqStr = eqStr.substring(0, eqStr.length - 1);
	}
	return eqStr;
}
/**
 * 入参check
 * @param {Object} jsondate
 */
function checkParams(jsondate) {
	var jsonStr = "{";
	var returnFlag = false;
	for(var x in jsondate) {
		if(jsondate[x] == undefined || jsondate[x] == null) {
			console.log(x + "入参为空");
			returnFlag = true;
		}
	}
	return returnFlag;
}
/**
 * 资源路径的check
 */
function checkZylj(beforeSubStr) {
	var zylj = "";
	if(beforeSubStr.indexOf("http") > -1) {
		zylj = beforeSubStr;
	} else if(beforeSubStr.length > 0) {
		zylj = filesHost + beforeSubStr;
	}
	return zylj;
}
/**
 * 删除原有的list（刷新用）
 */
function removeLi(id) {
	var objUl = document.getElementById(id);

	if(!isEmpty(objUl)) {
		var objLi = objUl.getElementsByTagName("li");
		var length = objLi.length;
		for(var i = 0; i < length; i++) {
			objUl.removeChild(objLi[0]);
		}
	} else {
		mui.toast("刷新失败");
	}
}

function showEle(ele) {
	if(ele.classList.contains("mui-hidden")) {
		ele.classList.remove("mui-hidden");
	}
}

function hiddenEle(ele) {
	if(!ele.classList.contains("mui-hidden")) {
		ele.classList.add("mui-hidden");
	}
}

function hiddenEleByParent(parentEle, targetEle) {
	var eleArr = parentEle.getElementsByTagName(targetEle);
	for(var i = 0; i < eleArr.length; i++) {
		if(!eleArr[i].classList.contains("mui-hidden")) {
			eleArr[i].classList.add("mui-hidden");
		}
	}
}

function isShow(ele) {
	if(ele.classList.contains("mui-hidden")) {
		return false;
	} else {
		return true;
	}
}

function addClass(className, ele) {
	if(!ele.classList.contains(className)) {
		ele.classList.add(className)
	}
}

function deleteClass(className, ele) {
	if(ele.classList.contains(className)) {
		ele.classList.remove(className)
	}
}

/**
 * 错误信息弹窗 
 * @param {Object} data
 * @param {Object} code
 */
function toastMesg(data, code1, code2) {
	if(!isEmpty(data)) {
		if(!isEmpty(data.code)) {
			if(code1 > data.code || code2 <= data.code) {
				mui.toast(data.mesg);
			}
		}
	}
}

/**
 *日志打印方法  logFlag控制日志打印
 */
var logFlag = true;

function logText(text) {
	if(logFlag) {
		console.log(text);
	}
}

function formatTimeForTimestamp(timestamp) {
	var date = new Date(timestamp); //获取一个时间对象
	var year = date.getFullYear(); // 获取完整的年份(4位,1970)
	var month = date.getMonth() + 1; // 获取月份(0-11,0代表1月,用的时候记得加上1)
	var day = date.getDate(); // 获取日(1-31)
	var hours = date.getHours(); // 获取小时数(0-23)
	var minutes = date.getMinutes(); // 获取分钟数(0-59)
	var seconds = date.getSeconds(); // 获取秒数(0-59)
	return year + "-" + month + '-' + day;
}

function formatDateTimeForDate(date) {
	var year = date.getFullYear(); // 获取完整的年份(4位,1970)
	var month = date.getMonth() + 1; // 获取月份(0-11,0代表1月,用的时候记得加上1)
	var day = date.getDate(); // 获取日(1-31)
	var hours = date.getHours(); // 获取小时数(0-23)
	var minutes = date.getMinutes(); // 获取分钟数(0-59)
	var seconds = date.getSeconds(); // 获取秒数(0-59)
	return year + "-" + month + '-' + day + " " + hours + ":" + minutes + ":" + seconds;
}

function backWindowChangeColor(color) {
	if(isEmpty(color)) {
		color = "#FFFFFF";
	}
	var currentWebview = plus.webview.currentWebview();
	currentWebview.close();
	plus.navigator.setStatusBarBackground(color);
}

function returnFloat(value) {
	var value = Math.round(parseFloat(value) * 100) / 100;
	var xsd = value.toString().split(".");
	if(xsd.length == 1) {
		value = value.toString() + ".00";
		return value;
	}
	if(xsd.length > 1) {
		if(xsd[1].length < 2) {
			value = value.toString() + "0";
		}
		return value;
	}
}

Array.prototype.remove = function(dx)　 {　　
	if(isNaN(dx) || dx > this.length) {
		return false;
	}　　
	for(var i = 0, n = 0; i < this.length; i++)　　 {　　　　
		if(this[i] != this[dx])　　　　 {　　　　　　
			this[n++] = this[i]　　　　
		}　　
	}　　
	this.length -= 1　
}

function arrayDelete(array, value) {
	for(var i = 0; i < array.length; i++) {
		if(array[i] == value) {
			array.remove(i);
		}
	}
}

function getLocationPoint(callback) {
	if(navigator.geolocation) {
		alert("524");
		navigator.geolocation.getCurrentPosition(
			function(position) {
				alert("525");
				var longitude = position.coords.longitude;
				var latitude = position.coords.latitude;
				callback(longitude , latitude);
				console.log(longitude)
				console.log(latitude)
			},
			function(e) {
				var msg = e.code;
				var dd = e.message;
				alert("858");
				console.log(msg)
				console.log(dd)
			}
		)
	} else {
		alert("666");
	}
}


var emptyDiv = document.getElementById("emptyDiv");

function emptyShow(tips, height, id) {
	emptyDiv = document.getElementById("emptyDiv");
	if(isEmpty(emptyDiv)) {
		var createDiv = document.createElement("div");
		createDiv.id = "emptyDiv";
		createDiv.className = "null-list-div";
		createDiv.style.height = height + 'px';
		createDiv.innerHTML = '<img src="../../../ui/index/images/no_bill.png" /><br /><span>' + tips + '</span>';
		document.body.appendChild(createDiv);
		insertAfter(createDiv, document.getElementById(id));
	} else {
		showEle(emptyDiv);
	}
}

function hideEmptyDiv() {
	emptyDiv = document.getElementById("emptyDiv");
	if(!isEmpty(emptyDiv)) {
		hiddenEle(emptyDiv);
	}
}

function openBigImage(src, isHeader) {
	var bigImage = document.getElementById("bigImg");

	if(!isEmpty(bigImage)) {
		console.log('show');
		bigImage.src = src;
		showEle(bigImage);
		return;
	}

	if(isHeader == null || isHeader == undefined) {
		isHeader = false;
	}
	var imageView = document.createElement("img");
	imageView.id = "bigImg";
	imageView.className = "big-img";
	var viewHeagth = document.body.clientHeight;
	if(isHeader) {
		viewHeagth = viewHeagth - $("#header").height() + "px";
	}
	imageView.style.height = viewHeagth;
	imageView.style.top = $("#header").height() + "px";
	imageView.src = src;
	$(".mui-content").append(imageView);

	$("#bigImg").on('tap', function() {
		hideBigImage();
	});

}

function hideBigImage() {
	var bigImage = document.getElementById("bigImg");
	if(!isEmpty(bigImage)) {
		hiddenEle(bigImage);
	}
}

function getPhoto(imageView, isUpload, callBack) {

	if(isUpload == null || isUpload == undefined) {
		isUpload = true;
	}

	var btnArray = [{
		title: "拍照"
	}, {
		title: "从相册中选择"
	}];
	var text = "";
	plus.nativeUI.actionSheet({
		title: "选择图片",
		cancel: "取消",
		buttons: btnArray
	}, function(e) {
		var index = e.index;
		switch(index) {
			case 0:
				text = "取消选择图片";
				break;
			case 1:
				getImage(imageView, isUpload, callBack);
				break;
			case 2:
				galleryImg(imageView, isUpload, callBack);
				break;
		}
	});
}

function getImage(imageView, isUpload, callBack) {
	var cmr = plus.camera.getCamera();
	cmr.captureImage(function(path) {
		//		plus.gallery.save(path, function() {
		//
		//		}, function(e) {
		//			mui.toast("拍摄照片失败，请重试");
		//		});

		plus.io.resolveLocalFileSystemURL(path, function(entry) {
			var imgEle = imageView;
			imgEle.src = entry.fullPath;
		}, function() {
			mui.toast("拍摄照片失败，请重试");
		});

		console.log("path==>>" + path);
		plus.zip.compressImage({
				src: path,
				dst: path,
				overwrite: true,
				quality: 20
			},
			function() {
				if(isUpload) {
					createUpload(path, callBack);
				} else {
					callBack(path);
				}

			},
			function(error) {
				alert("图片上传失败，请重新选择！");
			});
	}, function(e) {
		mui.toast('取消拍照');
	}, {
		filename: '_doc/gallery/',
		index: 1
	});
}

function galleryImg(imageView, isUpload, callBack) {
	// 从相册中选择图片
	plus.gallery.pick(function(path) {

		var imgEle = imageView;
		imgEle.src = path;
		plus.zip.compressImage({
				src: path,
				dst: path,
				overwrite: true,
				quality: 20
			},
			function() {

				if(isUpload) {
					createUpload(path, callBack);
				} else {
					callBack(path);
				}
			},
			function(error) {
				alert("图片上传失败，请重新选择！");
			});

	}, function(e) {
		mui.toast('取消选择图片');
	}, {
		filter: 'image'
	});
}

function createUpload(path, callback) {
	console.log(path);
	plus.nativeUI.showWaiting();
	var task = plus.uploader.createUpload(getRequestAddressUrl('base'), {
		method: "POST",
		priority: 100
	}, function(t, status) {
		plus.nativeUI.closeWaiting();
		// 上传完成
		if(status == 200) {
			console.log(JSON.stringify(t));
			var result = JSON.parse(t.responseText);
			callback(result);
		} else {
			mui.toast("上传失败!");
		}
	});
	var length = path.split("/").length - 1;
	var name = path.split("/")[length];
	task.addFile(path, {
		key: "f",
		name: name,
		mime: "image/jpeg"
	});
	
	var jsonDate = {
		"op": "uploadfile",
		"uid": userInfo.user_id,
		system: systemName
	}
	task.addData("p", JSON.stringify(jsonDate));
	task.addData("alert", "1");
	task.start();
}

function exSubmit(parames, images, callback) {
	plus.nativeUI.showWaiting();
	var task = plus.uploader.createUpload(getRequestAddressUrl('base'), {
		method: "POST",
		priority: 100
	}, function(t, status) {
		plus.nativeUI.closeWaiting();
		// 上传完成
		if(status == 200) {
			console.log(JSON.stringify(t));
			var result = JSON.parse(t.responseText);
			callback(result);
		} else {
			mui.toast("上传失败!");
		}
	});
	var num = images.length;
	console.log(images.length);
	for(var i = 0; i < images.length; i++) {
		var path = images[i].src;
		if(path.indexOf("add_photo") > -1) {
			num--;
			continue;
		}
		var length = path.split("/").length - 1;
		var name = path.split("/")[length];
		var positionNo = i + 1;
		task.addFile(path, {
			key: "image" + positionNo,
			name: name,
			mime: "image/jpeg"
		});
	}
	if(userInfo) {
		parames.uid = userInfo.user_id;
		parames.system = systemName;
		parames.num = num;
	}
	console.log(JSON.stringify(parames));
	task.addData("p", JSON.stringify(parames));
	task.addData("alert", "1");
	task.start();
}